﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Rud.Holmgren.Tabulex3000.Controls
{
    public class MatrixPanel : Panel
    {
        public int NCols { get; set; }

        private List<UIElement[]> GetRows()
        {
            var retval = new List<UIElement[]>();
            var offset = 0;
            
            var children = Children.OfType<UIElement>().ToList();

            while (offset < children.Count)
            {
                retval.Add(children.Skip(offset).Take(NCols).ToArray());
                offset += NCols;
            }

            return retval;
        }

        protected override Size MeasureOverride(Size constraint)
        {
            var rows = GetRows();

            double height = 0;

            foreach (var r in rows)
            {
                double rowheight = 0;

                var elmconstraint = new Size(constraint.Width / NCols, Math.Max(0, constraint.Height - height));
                r.ToList().ForEach(e =>
                {
                    e.Measure(elmconstraint);
                    rowheight = Math.Max(rowheight, e.DesiredSize.Height);
                });

                height += rowheight;
            }

            return new Size(constraint.Width, height);
        }

        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            var rows = GetRows();
            double y = 0;

            foreach (var r in rows)
            {
                var rowheight = r.Max(e => e.DesiredSize.Height);
                double x = 0;

                foreach (var c in r)
                {
                    var rect = new Rect(x, y + (rowheight - c.DesiredSize.Height) / 2, arrangeBounds.Width / NCols, c.DesiredSize.Height);
                    c.Arrange(rect);

                    x += arrangeBounds.Width / NCols;
                }

                y += rowheight;
            }

            return new Size(arrangeBounds.Width, y);
        }

    }
}
